#!/usr/bin/env bash

TRUST_DNS="4.2.2.2"
NAT_DOMAIN="github.com"
NAT_OUTPUT="OUTPUT_GITHUB"

# 1. 创建 OUTPUT_GITHUB 链并清空此链

chain_exists=$(iptables -t nat -S | grep ${NAT_OUTPUT})
if [[ -z "${chain_exists}" ]]; then
    iptables -t nat -N ${NAT_OUTPUT}
fi
iptables -t nat -F ${NAT_OUTPUT}

# 2. 将 NAT_OUTPUT 链添加到 OUTPUT 规则中
chain_exists_children=$(iptables -t nat -S OUTPUT | grep ${NAT_OUTPUT})
if [[ -z "${chain_exists_children}" ]]; then
    iptables -t nat -A OUTPUT -j ${NAT_OUTPUT}
fi

# 3. 检查点：如果不需要进行配置:
    # 3.1 清空 NAT_OUTPUT 链
    # 3.2 移除 OUTPUT 规则中的 NAT_OUTPUT 链
    # 3.3 删除 NAT_OUTPUT 链
if [[ "${1}" == "clean" ]]; then
    echo "remove iptables rules"
    iptables -t nat -D OUTPUT -j ${NAT_OUTPUT}
    iptables -t nat -F ${NAT_OUTPUT}
    iptables -t nat -X ${NAT_OUTPUT}
    exit 0
fi

# 4. 获取 NAT_DOMAIN 的 fake_ip 转发到 trust_ip
nslookup_fake_ip=$(nslookup ${NAT_DOMAIN} | grep "Address: " | awk '{print $2}' | head -n 1)
nslookup_trust_ip=$(nslookup ${NAT_DOMAIN} ${TRUST_DNS}| grep "Address: " | awk '{print $2}' | head -n 1)
if [[ -z "${nslookup_fake_ip}" ]]; then
    echo "empty fake_ip"
    exit 0
fi

if [[ -z "${nslookup_trust_ip}" ]]; then
    echo "empty trust_ip"
    exit 0
fi

# 5. 配置 NAT_OUTPUT 链规则，将 fake_ip 转发到 trust_ip
iptables -t nat -A ${NAT_OUTPUT} -d "${nslookup_fake_ip}/32" -j DNAT --to-destination "${nslookup_trust_ip}"

echo -e "apply iptables rules: \n\t ${NAT_DOMAIN}: ${nslookup_fake_ip} -> ${nslookup_trust_ip}"